<!-- 保险公司编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="500"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="车辆信息" prop="vehicle_id" v-if="!isUpdate">
        <span
          class="blue pointer"
          v-if="form.vehicle_id == 0"
          @click="openVehicle"
          >请选择</span
        >
        <span class="blue pointer" @click="openVehicle" v-else>{{
          selectedVehicle
        }}</span>
      </el-form-item>

      <el-form-item label="分类" prop="cate_id">
        <el-select
          clearable
          v-model="form.cate_id"
          placeholder="请选所属分类"
          style="width: 250px"
          filterable
        >
          <el-option
            v-for="item in cateList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
            {{ item.title }}
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="类型" prop="io_type">
        <el-radio-group v-model="form.io_type">
          <el-radio-button label="收入">收入</el-radio-button>
          <el-radio-button label="支出">支出</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="金额" prop="amount">
        <el-input
          v-model="form.amount"
          style="width: 200px"
          @input="handleInput(row)"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item
        label="收款日期"
        prop="belongs_date"
        v-if="form.io_type == '收入'"
      >
        <el-date-picker
          v-model="form.belongs_date"
          type="date"
          style="width: 150px"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" />
      </el-form-item>

      <el-form-item label="相关图片" prop="images">
        <image-upload :limit="99" v-model="form.images" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
    <vehicle v-model="showVehicle" @done="chooseDone" />
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import {
    updateVehicleIncomeExpense,
    pageVehicleIncomeExpenseCate
  } from '@/api/company';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  import Vehicle from '@/views/trade/components/choose-vehicle.vue';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    vehicle: Object
  });

  /** 是否是修改 */
  const isUpdate = ref(false);

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    vehicle_id: 0,
    plate_number: '',
    status: 0,
    amount: '',
    io_type: '',
    belongs_date: '',
    cate_id: '',
    remark: '',
    images: ''
  });

  const handleInput = (row) => {
    let value = row.amount;

    // 只允许输入数字、小数点和负号
    value = value.replace(/[^\d.-]/g, '');

    // 负号只能出现在最前面
    value = value.replace(/^-+/, '-').replace(/(.)-/g, '$1');

    // 确保只出现一个小数点
    value = value.replace(/(\..*)\./g, '$1');

    // 处理前导零，避免 0001 这种情况，允许 0.x 和 -0.x
    value = value.replace(/^-?0+(\d)/, '-$1');

    row.amount = value;
  };

  var validateIncomeExpenseDate = (rule, value, callback) => {
    if (form.io_type == '收入' && (value === '' || value === null)) {
      callback(new Error('请选择收款日期'));
    } else {
      callback();
    }
  };

  var validateVehicle = (rule, value, callback) => {
    console.log(value, '车辆ID');
    if (!value) {
      return callback(new Error('请选择车辆'));
    }

    if (!Number.isInteger(value)) {
      callback(new Error('请选择车辆'));
    } else {
      if (value == 0) {
        callback(new Error('请选择车辆'));
      } else {
        callback();
      }
    }
  };

  /** 表单验证规则 */
  const rules = reactive({
    vehicle_id: [
      {
        validator: validateVehicle,
        trigger: 'blur'
      }
    ],
    belongs_date: [
      {
        validator: validateIncomeExpenseDate,
        trigger: 'blur'
      }
    ],
    amount: [
      {
        required: true,
        message: '请输入金额',
        type: 'string',
        trigger: 'blur'
      }
    ],
    cate_id: [
      {
        required: true,
        message: '请选择分类',
        type: 'integer',
        trigger: 'blur'
      }
    ],
    io_type: [
      {
        required: true,
        message: '请选择收支类型',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 分类 */
  const cateList = ref([]);
  const getCateList = () => {
    pageVehicleIncomeExpenseCate({ limit: 99999999 })
      .then((res) => {
        cateList.value = res.list;
      })
      .catch((e) => {
        console.log(e);
      });
  };

  /** 选择车辆 */
  const showVehicle = ref(false);
  const openVehicle = () => {
    showVehicle.value = true;
  };
  /** 选择完车辆 */
  const selectedVehicle = ref('');
  const chooseDone = (e) => {
    console.log(e, '????');
    showVehicle.value = false;
    form.vehicle_id = e.id;
    selectedVehicle.value = e.plate_number + ' - ' + e.company;
    console.log(form, '好好的');
  };

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }

      loading.value = true;
      var requestData = Object.assign({}, form);

      updateVehicleIncomeExpense(requestData)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };
  const title = ref('');
  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        getCateList();
        // if (props.data) {
        //   form.vehicle_id = props.data.id;
        //   form.company = props.data.company;
        //   form.plate_number = props.data.plate_number;
        //   selectedVehicle.value =
        //     props.data.plate_number + ' - ' + props.data.company;
        // }
        title.value = '车辆收支';
        if (props.vehicle) chooseDone(props.vehicle);
        if (props.data) {
          assignFields({
            ...props.data
          });
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
